package com.example.passport.service;

import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.interceptor.UserContext;
import com.example.passport.dto.RoleCreateDto;
import com.example.passport.dto.RoleDto;
import com.example.passport.dto.RoleSearchDto;
import com.example.passport.entity.Role;
import com.example.passport.entity.User;
import com.example.passport.mapper.RoleMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RoleService {

    @Resource
    RoleMapper roleMapper;

    /**
     * 新增角色
     */
    public void createRole(RoleCreateDto roleCreateDto) {
        User me = UserContext.getUser();
        if (roleMapper.findByName(roleCreateDto.getName(), me.getTenantId()) != null) {
            throw new BusinessException("角色名重复");
        }
        Role role =new Role();
        role.setTenantId(me.getTenantId());
        BeanUtils.copyProperties(roleCreateDto, role);
        roleMapper.create(role);
    }

    /**
     * 列出角色
     */
    public ListDto<RoleDto> listRole(RoleSearchDto condition, Pagination pagination) {

        long total = roleMapper.count(condition);
        if (total <= 0) {
            return new ListDto<>(new ArrayList<>(), pagination);
        }

        pagination.setTotal(total);

        List<Role> roleList = roleMapper.findAll(condition, pagination);

        List<RoleDto> roleDtoList = roleList.stream().map(role -> {
            RoleDto roleDto = new RoleDto();
            BeanUtils.copyProperties(role, roleDto);
            return roleDto;
        }).collect(Collectors.toList());

        return new ListDto<>(roleDtoList, pagination);
    }

    /**
     *修改数据
     */
    public void update(@Valid RoleDto roleDto) {
        User me = UserContext.getUser();

        if (roleMapper.findByName( roleDto.getName(),me.getTenantId()) != null&& roleMapper.findByIdName(me.getTenantId(),roleDto.getId(),roleDto.getName()) == null ) {
            throw new BusinessException("名称已存在");
        }

        Role role = new Role();
        role.setTenantId(me.getTenantId());
        BeanUtils.copyProperties(roleDto, role);
        if (roleMapper.update(role) != 1) {
            throw new BusinessException("操作失败");
        }
    }

    /**
     *删除数据
     */
    public void delete(long id) {

        if (roleMapper.deleteById(id,UserContext.getUser().getTenantId()) != 1) {
            throw new BusinessException("操作失败");
        }
    }
    /**
     * 查找数据
     */
    public Role findById(long id,long tenantId){
        return roleMapper.findById(tenantId,id);
    }
}
